package org.example.demo3.server.Controller;

import lombok.extern.slf4j.Slf4j;
import org.example.demo3.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.example.demo3.common.result.Result;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        String filename = null;
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));  //截取文件后缀名
            filename = UUID.randomUUID().toString() + extension;
            aliOssUtil.upload(file.getBytes(), filename);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return Result.success(filename);
    }
}
